package integraltask

import (
	"context"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetIntegralTaskListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetIntegralTaskListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetIntegralTaskListLogic {
	return &BackendGetIntegralTaskListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetIntegralTaskListLogic) BackendGetIntegralTaskList(in *setting.BackendIntegralTaskListReq) (*setting.BackendIntegralTaskListResp, error) {
	logx.Infof("BackendGetIntegralTaskList in : %+v", in)
	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.SysUserIntegralTaskColumns.ID+order)
			}
			if orderBy.Field == "sort" {
				orderBys = append(orderBys, model.SysUserIntegralTaskColumns.Sort+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.SysUserIntegralTaskColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	var postType string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			case "type":
				postType = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	var withCount int
	var preCount int64
	filterMap := make(map[string]map[string][]any)
	resp := &setting.BackendIntegralTaskListResp{}
	if in.Ids != nil && len(*in.Ids) > 0 {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.SysUserIntegralTaskColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
			withCount = -1
			preCount = int64(len(vals))
		}
	}

	var statusIsSet bool
	var isAll bool
	statusMap := make(map[string][]any)
	switch postType {
	case "1": // 全部
		statusMap["notEqualTo"] = []any{globalkey.StatusDeleted}
		isAll = true
	case "2": // 进行中
		filterMap[model.SysUserIntegralTaskColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusEnabled},
		}
		statusIsSet = true
	case "3": // 已过期
		filterMap[model.SysUserIntegralTaskColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusExpired},
		}
		statusIsSet = true
	case "4": // 回收站
		filterMap[model.SysUserIntegralTaskColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusDeleted},
		}
		statusIsSet = true
	}
	if !restricted {
		page = in.Page
		pageSize = in.PageSize
		withCount = 1
	}

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) >= 2 {
		filterMap[model.SysUserIntegralTaskColumns.RuleName] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Name)},
		}
	}
	if in.Slug != nil && len(strings.TrimSpace(*in.Slug)) >= 2 {
		filterMap[model.SysUserIntegralTaskColumns.RuleSlug] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Slug)},
		}
	}
	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.SysUserIntegralTaskColumns.CreatedAt] = createdAtMap

	if isAll {
		ret, _, err := l.svcCtx.IntegralTask.GetList(l.ctx, model.M{
			"statistic": "1",
		}, 5, filterMap)
		if err != nil {
			// return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			logx.Errorw("BackendGetIntegralTaskList GetList statistic err", logx.Field("detail", err.Error()))
		} else if len(ret) > 0 {
			statusStatisticMap := make(map[uint32]uint32)
			var total uint16
			for _, v := range ret {
				statusStatisticMap[uint32(v.Status)] = uint32(v.Sort)
				if v.Status != uint8(globalkey.StatusDeleted) {
					total += v.Sort
				}
			}
			statusStatisticMap[uint32(5)] = uint32(total)
			resp.StatusStatisticMap = statusStatisticMap
		}
	}

	if !statusIsSet {
		statusIn := modelx.UniqueInterfaces(stati, 32)
		if len(statusIn) > 0 {
			statusMap["in"] = statusIn
		}
		if in.Status != nil {
			statusMap["equalTo"] = []any{*in.Status}
		}
		filterMap[model.SysUserIntegralTaskColumns.Status] = statusMap
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	}
	res, count, err := l.svcCtx.IntegralTask.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  orderBy,
	}, withCount, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if restricted {
		count = preCount
	}
	resp.Total = uint64(count)

	if len(res) > 0 {
		for _, v := range res {
			resp.List = append(resp.List, &setting.IntegralTaskInfo{
				Id:            pointy.GetPointer(v.ID),
				RuleName:      pointy.GetPointer(v.RuleName),
				RuleSlug:      pointy.GetPointer(v.RuleSlug),
				RuleType:      pointy.GetPointer(uint32(v.RuleType)),
				PicId:         pointy.GetPointer(v.PicID),
				PicUrl:        pointy.GetPointer(v.PicURL),
				Frequency:     pointy.GetPointer(uint32(v.Frequency)),
				Points:        pointy.GetPointer(v.Points),
				EffectiveTime: pointy.GetPointer(modelx.FormatTime(v.EffectiveTime, "")),
				Ip:            pointy.GetPointer(v.IP),
				Description:   pointy.GetPointer(modelx.FormatNullDotString(v.Description)),
				Sort:          pointy.GetPointer(uint32(v.Sort)),
				Status:        pointy.GetPointer(uint32(v.Status)),
				DelStatus:     pointy.GetPointer(uint32(v.DelStatus)),
				CreatedAt:     pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:     pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt:     pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
			})
		}
	}

	return resp, nil
}
